#!/bin/bash
rpath="$(readlink ${BASH_SOURCE})"
if [ -z "$rpath" ];then
    rpath=${BASH_SOURCE}
fi
root="$(cd $(dirname $rpath) && pwd)"
cd "$root"
source environment

user=${SUDO_USER:-$(whoami)}
home=$(eval echo ~$user)

exit_file_not_exist=1
exit_changed=2
exit_not_changed=3

usage(){
    cat<<-EOF
	Usage: $(basename $0)
	CMD:
	    start
	    stop
	    restart
	    status
	    config
	    pac
	    log
	    em
	EOF
}

makeConf(){
    #STEP 1 read privoxy.conf to get config
    pacConf="$(sed -n '/\[pac]/,/\[end]/p' $root/privoxy.conf)"
    # echo "$pacConf"
    pac_listen=$(echo "$pacConf" | grep 'listen-address' | awk -F'=' '{print $2}')
    pac_upstream=$(echo "$pacConf" | grep 'upstream' | awk -F'=' '{print $2}')
    pac_logdir=$(echo "$pacConf" | grep 'logdir' | awk -F'=' '{print $2}')
    pac_logfile=$(echo "$pacConf" | grep 'logfile' | awk -F'=' '{print $2}')

    globalConf=$(sed -n '/\[global]/,/\[end]/p' $root/privoxy.conf)
    global_listen=$(echo "$globalConf" | grep 'listen-address' | awk -F'=' '{print $2}')
    global_upstream=$(echo "$globalConf" | grep 'upstream' | awk -F'=' '{print $2}')
    global_logdir=$(echo "$globalConf" | grep 'logdir' | awk -F'=' '{print $2}')
    global_logfile=$(echo "$globalConf" | grep 'logfile' | awk -F'=' '{print $2}')

    cat<<-EOF
	Config:
	pac_listen: $pac_listen
	pac_upstream: $pac_upstream
	pac_logdir: $pac_logdir
	pac_logfile: $pac_logfile

	global_listen: $global_listen
	global_upstream: $global_upstream
	global_logdir: $global_logdir
	global_logfile: $global_logfile
	EOF

    #STEP 2replace global.config pac.config pac-header.action with config readed by step 1 and generate a runtime config file
    mkdir runtime >/dev/null 2>&1
    sed -e "s|LISTEN-ADDRESS|$global_listen|g" -e"s|UPSTREAM|$global_upstream|g" -e "s|LOGDIR|$global_logdir|g" -e "s|LOGFILE|$global_logfile|g" "$root/global.config" > runtime/global.config
    sed -e "s|LISTEN-ADDRESS|$pac_listen|g"  -e "s|LOGDIR|$pac_logdir|g" -e "s|LOGFILE|$pac_logfile|g" -e "s|ROOT|$root|g" "$root/pac.config" > runtime/pac.config
    sed -e "s|UPSTREAM|$pac_upstream|g" pac-header.action gfwlist custom-pac.action > runtime/pac.action
}

config(){
    # editor=vi
    # if command -v vim >/dev/null 2>&1;then
    #     editor=vim
    # fi
    # $editor "$root/privoxy.conf"
    modify "$root/privoxy.conf"
    case $? in
        $exit_file_not_exist)
            echo "Config file not exit"
            ;;
        $exit_changed)
            echo "Config file changed,restart service..."
            makeConf
            stop
            start
            echo "Done."
            ;;
        $exit_not_changed)
            echo "Nothing happened."
            ;;
    esac
}

start(){
    #tmux new-session -d -s "pac" privoxy --no-daemon --pidfile /tmp/pac.privoxy.pid $root/runtime/pac.config
    #tmux new-window -d -t "privoxy"  privoxy --no-daemon --pidfile /tmp/global.privoxy.pid $root/runtime/global.config
    #tmux new-session -d -s "global"  privoxy --no-daemon --pidfile /tmp/global.privoxy.pid $root/runtime/global.config
    if [ ! -e runtime/global.config ] || [ ! -e runtime/pac.config ];then
        echo "No config file found,run $(basename $0) makeConf to generate it"
        exit 1
    fi
    case $(uname) in
        Linux)
            if (($EUID!=0));then
                sudo systemctl start $PAC_PRIVOXY
                sudo systemctl start $GLOBAL_PRIVOXY
            else
                systemctl start $PAC_PRIVOXY
                systemctl start $GLOBAL_PRIVOXY
            fi
            ;;
        Darwin)
            #TODO
            makeConf
            launchctl load -w $home/Library/LaunchAgents/pac.privoxy.plist
            launchctl load -w $home/Library/LaunchAgents/global.privoxy.plist
            ;;
    esac
}

stop(){
    #tmux kill-session -t "pac"
    #tmux kill-session -t "global"
    case $(uname) in
        Linux)
            if (($EUID!=0));then
                sudo systemctl stop $PAC_PRIVOXY
                sudo systemctl stop $GLOBAL_PRIVOXY
            else
                systemctl stop $PAC_PRIVOXY
                systemctl stop $GLOBAL_PRIVOXY
            fi
            ;;
        Darwin)
            echo "launchctl unload -w $home/Library/LaunchAgents/pac.privoxy.plist"
            launchctl unload -w $home/Library/LaunchAgents/pac.privoxy.plist
            echo "launchctl unload -w $home/Library/LaunchAgents/global.privoxy.plist"
            launchctl unload -w $home/Library/LaunchAgents/global.privoxy.plist
            ;;
    esac
    #kill $(cat /tmp/pac.privoxy.pid)
    #kill $(cat /tmp/global.privoxy.pid)
}

status(){
    case $(uname) in
        Linux)
            systemctl status $PAC_PRIVOXY
            systemctl status $GLOBAL_PRIVOXY
            ;;
        Darwin)
            launchctl list | grep $PAC_PRIVOXY
            launchctl list | grep $GLOBAL_PRIVOXY
            ;;
    esac
}

modify(){
    f=$1
    if [ ! -e $f ];then
        return $exit_file_not_exist
    fi

    editor=vi
    if command -v vim>/dev/null 2>&1;then
        editor=vim
    fi
    case $(uname) in
        Linux)
            stat=stat
            ;;
        Darwin)
            stat='stat -x'
            ;;
    esac
    currentMTime=$($stat $f | grep 'Modify')
    $editor $f
    newMTime=$($stat $f | grep 'Modify')
    if [ "$currentMTime" != "$newMTime" ];then
        return $exit_changed
    else
        return $exit_not_changed
    fi
}
pac(){
    modify custom-pac.action
    case $? in
        $exit_file_not_exist)
            echo "pac file not exit"
            ;;
        $exit_changed)
            echo "pac file changed,restart service..."
            stop
            start
            echo "Done."
            ;;
        $exit_not_changed)
            echo "Nothing happened."
            ;;
    esac
}

log(){
    tail -f /tmp/privoxy.log
}

em(){
    editor=vi
    if command -v vim>/dev/null 2>&1;then
        editor=vim
    fi
    $editor ${BASH_SOURCE}
}

cmd=$1

case $cmd in
    #makeConf cmd used in pac.privoxy and global.privoxy
    makeConf)
        makeConf
        # export -f makeConf
        # if [[ $EUID -eq 0 ]] && [[ -n $SUDO_USER ]];then
        #     su $SUDO_USER -c "/bin/bash -c makeConf"
        # else
        #     makeConf
        # fi
        ;;
    start)
        start
        ;;
    restart)
        stop
        start
        ;;
    stop)
        stop
        ;;
    pac)
        pac
        ;;
    config)
        config
        ;;
    status)
        status
        ;;
    log)
        log
        ;;
    em)
        em
        ;;
    *)
        usage
        ;;
esac
